package com.school.dao.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.school.dao.ClassesDao;
import com.school.domain.Classes;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class ClassesDaoImpl implements ClassesDao {
    private DataSource dataSource = new ComboPooledDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);

    @Override
    public boolean add(Classes classes) {
        int result = 0;
        try {
            result = queryRunner.update("insert into classes values(?, ?, ?)", null, classes.getName(), classes.getNum());

        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }

    @Override
    public boolean del(long clid) {
        int result = 0;
        try {
            result = queryRunner.update("delete from classes where clid = ?", clid);
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }

    @Override
    public boolean del(String name) {
        int result = 0;
        try {
            result = queryRunner.update("delete from classes where name = ?", name);
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }

    @Override
    public boolean update(Classes classes) {
        int result = 0;
        try {
            result = queryRunner.update("update classes set name = ?, num = ? where clid = ?", classes.getName(), classes.getNum(), classes.getClid());
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }


    @Override
    public Classes findById(long clid) {
        List<Classes> execute = null;
        try {
            execute = queryRunner.query("select * from classes where clid = " + clid, new BeanListHandler<Classes>(Classes.class));
        } catch (SQLException throwables) {
            return null;
        }
        if (execute.size() < 1) return null;
        return execute.get(0);
    }

    @Override
    public Classes findByName(String name) {
        List<Classes> execute = null;
        try {
            execute = queryRunner.query("select * from classes where name = " + name, new BeanListHandler<Classes>(Classes.class));
        } catch (SQLException throwables) {
            return null;
        }
        if (execute.size() < 1) return null;
        return execute.get(0);
    }

    @Override
    public List<Classes> findAll() {
        List<Classes> execute = null;
        try {
            execute = queryRunner.query("select * from classes", new BeanListHandler<Classes>(Classes.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }
}
